/* eslint-disable no-restricted-syntax */
const { archi, lock } = require('../../utils/archi');

module.exports = () => async (ctx, next) => {
  const { app, socket } = ctx;
  const { query } = socket.handshake;
  const ns = await app.io.of('/');
  const roomId = query.id;
  let sockets = [];
  socket.join(query.id);
  for (const id in ns.connected) {
    if (roomId) {
      const rooms = Object.values(ns.connected[id].rooms);
      const index = rooms.indexOf(roomId);
      if (index !== -1) {
        sockets.push(ns.connected[id]);
      }
    }
  }

  let userList = {};
  sockets.forEach(item => {
    userList[item.handshake.query.account] = item.handshake.query.username;
  });

  userList[query.account] = query.username;

  ns.to(query.id).emit(
    'usernameList',
    Object.keys(userList).map(key => userList[key])
  );
  socket.emit(
    'usernameList',
    Object.keys(userList).map(key => userList[key])
  );
  if (!lock[query.id]) {
    lock[query.id] = {};
  }
  socket.emit('initLock', lock[query.id]);
  await next();

  sockets = [];

  for (const id in ns.connected) {
    if (roomId) {
      const rooms = Object.values(ns.connected[id].rooms);
      const index = rooms.indexOf(roomId);
      if (index !== -1) {
        sockets.push(ns.connected[id]);
      }
    }
  }

  if (sockets.length === 0) {
    await app.mysql.query(`update project set architecture=? where id=?`, [
      JSON.stringify(archi[query.id]),
      query.id,
    ]);
    delete archi[query.id];
    delete lock[query.id];
  }

  userList = {};
  sockets.forEach(item => {
    userList[item.handshake.query.account] = item.handshake.query.username;
  });

  ns.to(query.id).emit(
    'usernameList',
    Object.keys(userList).map(key => userList[key])
  );
};
